package com.whfc.openapi.api.hdc.controller;

import com.whfc.common.result.Result;
import com.whfc.common.result.ResultUtil;
import com.whfc.hdc.dto.AlgDeviceConfigDetailDTO;
import com.whfc.hdc.dto.HdcAccessTokenDTO;
import com.whfc.hdc.params.HdcOpenApiTokenParam;
import com.whfc.openapi.constant.OpenApiConst;
import com.whfc.openapi.api.hdc.service.HdcAlgOpenService;
import com.whfc.openapi.api.sys.service.OpenApiTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * 算法盒子接口
 *
 * @author qzexing
 * @version 1.0
 * @date 2021-07-20 09:33
 */
@RestController
@RequestMapping("/open/api/v2/hdc/alg")
public class HdcAlgOpenController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OpenApiTokenService openApiTokenService;

    @Autowired
    private HdcAlgOpenService hdcAlgOpenService;

    @PostMapping("/auth/token")
    public Result authToken(@RequestBody HdcOpenApiTokenParam param) {
        logger.info("算法盒子token获取token, param:[{}]", param);
        HdcAccessTokenDTO tokenDTO = openApiTokenService.getHdcOpenApiToken(param);
        if (tokenDTO != null) {
            hdcAlgOpenService.init(tokenDTO.getSn());
        }
        return ResultUtil.success(tokenDTO);
    }

    @GetMapping("/config")
    public Result getConfig(@RequestAttribute(OpenApiConst.OPENAPI_HDC_CLIENT) HdcAccessTokenDTO clientDTO) {
        logger.info("获取配置信息, sn:{}", clientDTO.getSn());
        AlgDeviceConfigDetailDTO configDetailDTO = hdcAlgOpenService.getConfig(clientDTO.getSn());
        return ResultUtil.success(configDetailDTO);
    }


    @PostMapping("/result/upload")
    public Result resultUpload(@RequestAttribute(OpenApiConst.OPENAPI_HDC_CLIENT) HdcAccessTokenDTO clientDTO,
                               @RequestParam("type") Integer type,
                               @RequestParam("time") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date time,
                               @RequestParam("file") MultipartFile file) {
        logger.info("上报算法识别结果, sn:{}, type:{}, time:{}, file:{}", clientDTO.getSn(), type, time, file.getOriginalFilename());
        hdcAlgOpenService.uploadResult(clientDTO.getSn(), type, time, file);
        return ResultUtil.success();
    }


}
